package com.kangjia.config;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.kangjia.general.dao.interceptor.TableInterceptor;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class HibernateConfig {

	@Value("${hibernate.dialect}")
	private String dialect;
	@Value("${hibernate.hbm2ddl.auto}")
	private String auto;
	@Value("${hibernate.show_sql}")
	private String show;
	@Value("${hibernate.format_sql}")
	private String format;
	@Value("${hibernate.temp.use_jdbc_metadata_defaults}")
	private String temp;
	@Value("${hibernate.mapping.path}")
	private String path;

	@Bean
	public LocalSessionFactoryBean localSessionFactoryBean(DruidDataSource druidDataSource) {
		LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
		localSessionFactoryBean.setDataSource(druidDataSource);
		Properties properties = localSessionFactoryBean.getHibernateProperties();
		properties.setProperty("hibernate.hbm2ddl.auto", auto);
		properties.setProperty("hibernate.dialect", dialect);
		properties.setProperty("hibernate.show_sql", show);
		properties.setProperty("hibernate.format_sql", format);
		properties.setProperty("hibernate.temp.use_jdbc_metadata_defaults", temp);
		String[] packagesToScan = path.split(",");
		localSessionFactoryBean.setPackagesToScan(packagesToScan);
		localSessionFactoryBean.setEntityInterceptor(new TableInterceptor());
		return localSessionFactoryBean;
	}

	@Bean
	public HibernateTransactionManager hibernateTransactionManager(SessionFactory sessionFactory) {
		HibernateTransactionManager transaction = new HibernateTransactionManager();
		transaction.setSessionFactory(sessionFactory);
		transaction.setRollbackOnCommitFailure(true);
		return transaction;
	}
	
}